<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleCancel" center width="40%">
      <el-form label-width="80px" ref="editFormRef" :model="editForm" :rules="rules">
        <el-form-item label="类型" prop="tag">
          <el-select :disabled="disableItem" v-model="editForm.tag" placeholder="请选择类型" @change="typeChange">
            <el-option v-for="item in buildTypeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-row v-if="editForm.tag >= 2">
          <el-col :span="editForm.tag > 2 ? 12 : 24">
            <el-form-item label="位置" prop="buildId">
              <el-select
                v-model="editForm.buildId"
                clearable
                :disabled="disableItem"
                placeholder="请选择楼栋"
                @change="buildChange"
              >
                <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="editForm.tag > 2">
            <el-form-item prop="floorId">
              <el-select
                v-if="editForm.tag >= 3"
                v-model="editForm.floorId"
                clearable
                :disabled="disableItem"
                placeholder="请选择楼层"
              >
                <el-option v-for="item in floorList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name"  @input="nameLongFn" placeholder="请输入名称"></el-input>
        </el-form-item>

        <el-form-item
          label="图片"
          prop="mapUrl"
          :rules="[{ required: editForm.tag === 2, message: '请上传图片', trigger: ['change'] }]"
        >
          <el-upload
            class="avatar-uploader"
            action=""
            :auto-upload="true"
            :show-file-list="false"
            :http-request="handleUpload"
            accept=".jpg, .jpeg, .gif, .png, .bmp"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="editForm.mapUrl" :src="editForm.mapUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <!-- <el-form-item v-if="editForm.tag > 2" label="撒点" prop="positionStr">
          <el-button plain v-if="!editForm.positionStr" @click="positionFocus">尚未撒点</el-button>
          <el-input
            v-else
            ref="positionInput"
            placeholder="请设置坐标"
            @focus="positionFocus(true)"
            v-model="editForm.positionStr"
          ></el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="hanldeSave('editFormRef')">确 定</el-button>
      </div>
    </el-dialog>

    <dot-modal ref="dotModal" @dotModalOk="dotModalOk"></dot-modal>
  </div>
</template>

<script>
import { buildTypeList } from '@/views/children/dcenter/js/constants'
import pick from 'lodash.pick'
import { getListByTag, uploadImage, floorAdd, floorUpdate, getImgSource } from '@/views/children/safety/js/device'
import dotModal from './DotModal'
// import { createLogger } from 'vuex'

// let id = 0
// let tag = 0
export default {
  name: 'BuildingModal',
  data () {
    return {
      title: '角色新增',
      dialogVisible: false, // 编辑弹窗
      editForm: {
        tag: '',
        name: '',
        parentId: 0,
        level: '',
        mapUrl: '',
        buildId: '',
        floorId: '',
        // positionStr: '',
        mapX: '',
        mapY: ''
      },
      imgUrl: '',
      model: {},
      rules: {
        tag: [{ required: true, message: '请选择类型', trigger: 'change' }],
        name: [{ required: true, message: '请输入名称', trigger: 'change' }],
        buildId: [{ required: true, message: '请选择楼栋', trigger: 'change' }],
        floorId: [{ required: true, message: '请选择楼层', trigger: 'change' }]
        // positionStr: [{ required: true, message: '请设置坐标比', trigger: 'change' }]
      },
      buildTypeList,
      buildList: [], // 楼栋
      floorList: [], // 楼层
      disableItem: false
    }
  },
  components: { dotModal },
  methods: {
    // 类型改变
    typeChange (val) {
      this.$refs.editFormRef.clearValidate('mapUrl')
      // 查楼栋
      if (val >= 2) {
        this.getListByTag(0, 1, 'buildList')
      }
      // 存在楼栋,查楼层
      if (val > 2 && this.editForm.buildId) {
        this.getListByTag(this.editForm.buildId, 2, 'floorList')
      }
    },

    // 楼栋改变
    buildChange (val) {
      if (this.editForm.tag > 2) {
        // 选择区域或房间时获取楼层
        this.getListByTag(val, 2, 'floorList')
      }
    },
    // 获取楼层信息
    async getListByTag (parentId, tag, arr, id) {
      const params = {
        parentId,
        tag
        // tenantNo: localStorage.getItem('tenantNo')
      }
      const { data } = await getListByTag(params)
      this[arr] = data
      if (tag === 1 && id) {
        this.editForm.buildId = id
      }
      if (tag === 2 && id) {
        this.editForm.floorId = id
      }
    },

    nameLongFn () {
      let { name } = this.editForm
      if (!name) return
      let res = this.inputLength(this.editForm.name)
      if (typeof res === 'object') {
        // 长度大于30，且记录了当前的下标
        this.$message.warning('长度不能超过30个字符！')
        // this.isLong++
        this.editForm.name = name.slice(0, res.index)
      }
    },
    // 计算input长度
    inputLength (val) {
      var len = 0
      for (var i = 0; i < val.length; i++) {
        var a = val.charAt(i)
        if (a.match(/[^\x0-\xff]/ig) != null) {
          if (len >= 29) return { len, index: i }
          len += 2
        } else {
          if (len >= 30) return { len, index: i }
          len += 1
        }
      }
      return len
    },

    // 新增
    add () {
      this.edit({})
    },
    // 编辑
    edit (record) {
      console.log(record)
      this.dialogVisible = true
      this.model = Object.assign({}, record)
      if (record.id) {
        this.imgUrl = record.mapUrl
        this.title = `编辑-${record.name}`
        this.disableItem = true
        const { tag, level } = record
        let levelArr = level.split(';')
        if (tag > 1) {
          this.getListByTag(0, 1, 'buildList', +levelArr[0])
        }
        if (tag > 2) {
          this.getListByTag(levelArr[0], 2, 'floorList', +levelArr[1])
          // this.editForm.positionStr = `${mapX},${mapY}`
        }
        this.$nextTick(() => {
          Object.assign(this.editForm, pick(this.model, 'tag', 'name', 'mapUrl', 'level', 'parentId'))
        })
      } else {
        this.title = '新增'
      }
    },

    hanldeSave (editFormRef) {
      this.$refs[editFormRef].validate(async valid => {
        if (valid) {
          this.regroupData(this.editForm)
          let res, msg
          const values = {
            ...this.editForm,
            mapUrl: this.imgUrl
            // tenantNo: localStorage.getItem('tenantNo'),
            // positionStr: undefined
          }
          delete values.buildId
          delete values.floorId
          delete values.positionStr
          if (!this.model.id) {
            console.log(values)
            res = await floorAdd(values)
            msg = '保存成功！'
          } else {
            console.log(this.model)
            let query = {
              id: this.model.id,
              mapUrl: values.mapUrl,
              mapX: values.mapX,
              mapY: values.mapY,
              name: values.name,
              parentId: values.parentId,
              tag: values.tag
            }
            res = await floorUpdate(query)
            msg = '修改成功！'
          }
          if (res.code === 0) {
            this.$message.success(msg)
          } else {
            this.$message.warning(res.msg)
          }
          let expanded = `0;${this.editForm.level}`
          this.$emit('ok', expanded)
          this.handleCancel()
        }
      })
    },
    // 重组数据
    regroupData (val) {
      let { tag, buildId, floorId } = val
      if (tag === 2) {
        this.editForm.parentId = buildId
        this.editForm.level = buildId
      }
      if (tag > 2) {
        this.editForm.parentId = floorId
        this.editForm.level = `${buildId};${floorId}`
        // const posTempArr = this.editForm.positionStr.split(',')
        // this.editForm.mapX = posTempArr[0]
        // this.editForm.mapY = posTempArr[1]
      }
    },

    // 上传限制
    handleUpload (res) {
      let uploadFileObj = res.file
      this.fileUploadFun(uploadFileObj)
    },
    // 上传文件
    async fileUploadFun (fileObj) {
      let param = new FormData()
      param.append('file', fileObj)
      const { code, data } = await uploadImage(param)
      if (code === 0) {
        try {
          const resImg = await getImgSource(data)
          let blob = new Blob([resImg], {
            type: resImg.type
          })
          let url = window.URL.createObjectURL(blob)
          this.editForm.mapUrl = url
          this.imgUrl = data
          // console.log(this.editForm.mapUrl)
        } catch (e) {
          this.$message.warning('上传失败！')
        }
        this.$message.success('上传成功')
      } else {
        this.$message.warning('上传失败！')
      }
    },
    beforeAvatarUpload (file) {
      let typeArr = ['image/jpeg', 'image/png', 'image/jpg', 'image/bmp']
      const isJPG = typeArr.includes(file.type)
      // const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/BMP 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!')
      }
      return isJPG && isLt2M
    },

    // 获取焦点弹框
    // positionFocus (flag) {
    //   let row = {}
    //   const { floorId, name, positionStr } = this.editForm
    //   if (!floorId) return this.$message.info('请先选择楼层!')
    //   row['mapUrl'] = this.floorList.filter(e => e.id === floorId)[0].mapUrl
    //   row['spotName'] = name || '点'
    //   if (positionStr) {
    //     let tempArr = this.editForm.positionStr.split(',')
    //     if (tempArr.length === 2) {
    //       row['roomX'] = tempArr[0]
    //       row['roomY'] = tempArr[1]
    //     }
    //   }
    //   this.$refs.dotModal.add(row)
    //   if (flag) {
    //     this.$refs.positionInput.blur()
    //   }
    // },

    dotModalOk (val) {
      this.editForm.positionStr = val
    },

    // 关闭弹框
    handleCancel () {
      this.$refs.editFormRef.resetFields()
      this.dialogVisible = false
      this.disableItem = false
      this.model = {}
      this.imgUrl = ''
      this.editForm.buildId = ''
      this.editForm.floorId = ''
      this.editForm.parentId = 0
      this.editForm.level = ''
      this.editForm.mapUrl = ''
      this.editForm.mapX = ''
      this.editForm.mapY = ''
      this.editForm.positionStr = ''
      this.editForm.name = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
.el-dialog {
  .el-input,
  .el-select {
    width: 100%;
  }
}
/deep/ .el-dialog__body {
  padding-bottom: 0;
}
.avatar-uploader /deep/ {
  line-height: 1;
  .el-upload {
    box-sizing: border-box;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
}
.no-position {
  background: red;
}
</style>
